import { defineComponent, ref, unref, watch } from 'vue';
import { VxeGrid } from 'vxe-table';
import type { VxeGridInstance, VxeGridProps } from 'vxe-table';
import { deepMerge } from '@/utils';
import { get, isFunction, set } from 'lodash-es';

export default defineComponent({
  name: 'BasicVxeGrid',
  inheritAttrs: true,
  emits: ['register'],
  setup(props, { emit, expose, slots, attrs }) {
    const gridRef = ref<VxeGridInstance>();
    const propsRef = ref<Partial<VxeGridProps>>({});
    const setProps = async (props: VxeGridInstance) => {
      propsRef.value = deepMerge(unref(propsRef) || ({} as any), props);
      Object.keys(props).map((key) => {
        set(propsRef.value, key, props[key]);
      });
    };
    const setPropField = async (prop: string, value: any) => {
      set(propsRef.value, prop, value);
    };

    const getPropField = (prop: string): any => {
      return get(unref(propsRef), prop);
    };

    const getProps = (): VxeGridInstance => {
      return unref(propsRef) as VxeGridInstance;
    };

    const methods = {
      getGridRef: () => gridRef.value,
      setProps,
      getPropField,
      setPropField,
      getProps,
    };
    // 监听组件实例变化
    watch(
      () => gridRef.value,
      (instance) => {
        if (instance) {
          Object.keys(methods).map((key) => {
            if (!isFunction(instance[key])) {
              instance[key] = methods[key];
            }
          });
          emit('register', instance, function (_propsRef: VxeGridProps) {
            propsRef.value = _propsRef;
          });
        }
      },
      { immediate: true },
    );

    console.log(attrs, props, emit);

    // 暴露实例方法
    expose(methods);

    return () => {
      return <VxeGrid ref={gridRef} v-slots={slots} {...attrs} {...(propsRef.value ?? {})} />;
    };
  },
});
